# -*- coding: utf-8 -*-
"""
Created on Thu Mar  6 15:13:57 2025

@author: Julin
"""

import re
# from pdfminer.high_level import extract_text
# import PyPDF2 as pypdf
import fitz as mupdf

tmp_file_path = r'C:\Users\Julin\Downloads\tmp.pdf'

class Any2Txt:

    def __init__(self):
        pass
    
    def doc2txt(self,file):
        pass

    def pdf2txt(self,file):

        # pypdf2
        # reader = pypdf.PdfReader(file)        
        # text = ""
        # for page in reader.pages:
        #     text += page.extract_text() + "\n"
        
        # pdfminer
        # text = extract_text(file)
        
        document = mupdf.open(stream=file)
        text = ''
        # 逐页提取文本
        for page_num in range(len(document)):
            page = document.load_page(page_num)
            # 获取页面文本（保留段落格式）
            page_text = page.get_text("text")
            text += page_text + '\n'
        
        newtext = ''
        # 逐行处理文本
        for eachline in text.splitlines():
            eachline = eachline.replace(' ','')
            if eachline:  # 跳过空行
                newline = self.process_line(eachline)
                newtext += newline
        
        return newtext
                        
    def process_line(self,line):
        
        # 匹配页码，首尾是“-”的行
        pager_pattern = re.compile(r'^-\d{1}-$|^-\d{2}-$|^—\d{1}—$|^—\d{2}—$|\d{1}$|\d{2}$')
        if pager_pattern.match(line):
            line = ''
            
        # 匹配由“─”组成的行
        symbolline_pattern = re.compile(r'^[─═*]+$')
        if symbolline_pattern.match(line):
            line = '\n\n'

        # 匹配开头是（1）等格式的行
        newline_pattern = re.compile(r'^(（\d+）|\d{4}年\d{1,2}月\d{1,2}日$)') 
        if newline_pattern.match(line):
            line = '\n' + line
            
        # 匹配结尾是。等格式的行 
        endline_pattern = re.compile(r'^.+[:：;；。]$|^.+的决定$')
        if endline_pattern.match(line): 
            line = line + '\n'
            
        # 匹配特殊行
        special_pattern = re.compile(r'^上海证券交易所$|^深圳证券交易所$|^当事人.+|^.+第\d+号$|^（[一二三四五六七八九十]+）|^[一二三四五六七八九十]+、')
        if special_pattern.match(line):
            line =  '\n' + line + '\n'
        
        return line
